package org.jing.ext.spring;

import org.jing.core.logger.JingLogger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Scope;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * Description: 应用上下文, 需要提前在main方法里注册才能使用其静态方法, 否则会空指针 <br>
 *
 * @author bks <br>
 * @since 2023-01-28 <br>
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class SpringbootApplicationContext implements ApplicationContextAware {
    private static final JingLogger LOGGER = JingLogger.getLogger(SpringbootApplicationContext.class);

    private volatile static SpringbootApplicationContext instance = null;

    private ApplicationContext context;

    @Override
    public void setApplicationContext(org.springframework.context.ApplicationContext applicationContext) throws BeansException {
        if (null == instance) {
            synchronized (SpringbootApplicationContext.class) {
                if (null == instance) {
                    LOGGER.info(">>>ApplicationContext Register Start<<<");
                    instance = new SpringbootApplicationContext();
                    instance.context = applicationContext;
                    LOGGER.info(">>>ApplicationContext Register Success<<<");
                }
            }
        }
    }

    private static SpringbootApplicationContext getApplicationContext() {
        return instance;
    }

    /**
     * Description: 根据名字获取Bean <br>
     *
     * @param name 名字 <br>
     * @return <br>
     */
    public static Object getBean(String name) {
        return getApplicationContext().context.getBean(name);
    }

    /**
     * Description: 根据类去获取Bean <br>
     *
     * @param clazz 类 <br>
     * @param <T> 类应该标注为@Component等被springboot管理的注解<br>
     * @return <br>
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().context.getBean(clazz);
    }

    /**
     * Description: 根据名字和类去获取Bean <br>
     *
     * @param name 名字 <br>
     * @param clazz 类 <br>
     * @param <T> 类应该标注为@Component等被springboot管理的注解<br>
     * @return <br>
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().context.getBean(name, clazz);
    }
}

